package com.phoenix;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestOperations;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;

import java.util.Arrays;

@SpringBootApplication
@EnableOAuth2Client
public class BootOauthClientApplication extends SpringBootServletInitializer {

	public static void main(String[] args) {
		SpringApplication.run(BootOauthClientApplication.class, args);
	}

	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
		return application.sources(BootOauthClientApplication.class);
	}

	/**
	 * The heart of our interaction with the resource; handles redirection for authentication, access tokens, etc.
	 * @param oauth2ClientContext
	 * @return
	 */
	@Bean
	public OAuth2RestOperations restTemplate(OAuth2ClientContext oauth2ClientContext) {
		return new OAuth2RestTemplate(resource(), oauth2ClientContext);
	}

	private OAuth2ProtectedResourceDetails resource() {
		AuthorizationCodeResourceDetails resource = new AuthorizationCodeResourceDetails();
		resource.setClientId("sampleClientId");
		resource.setClientSecret("secret");
		resource.setAccessTokenUri("http://localhost:8080/oauth/token");
		resource.setUserAuthorizationUri("http://localhost:8080/oauth/authorize");
		resource.setScope(Arrays.asList("read"));
		return resource;
	}
}

